
package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class AutentificationFilter implements Filter{

    private FilterConfig filterConfig;
    private String loginPage;

    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
        if (filterConfig != null) {
           loginPage = filterConfig.getInitParameter("login_page"); 
       }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpSession session = ((HttpServletRequest)request).getSession(true);
        String logged = (String)session.getAttribute("logged");
        if(logged == null){
            //si no hay usuario, redirigir a loginPage
        	session.setAttribute("flash", "Debes autenticarte en el sitio antes de continuar");
            filterConfig.getServletContext().getRequestDispatcher(loginPage).forward(request, response);
            return;
        }
        chain.doFilter(request, response);
        return;  
    }

    public void destroy(){
    }
}